#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

const std::string wwwroot = "./wwwroot";
const std::string homepage = "index.html";

class HttpRequest
{
public:
    void deserializer(const std::string& req)
    {
        size_t begin = 0, pos = 0;
        while (true)
        {
            pos = req.find("\r\n", begin);
            if (pos == std::string::npos)
                break;
            _header.push_back(req.substr(begin, pos - begin));
            begin = pos + 1;
            if (_header.back().empty())
                break;
        }
        begin += 1;
        _body = req.substr(begin, req.size() - begin);
    }
    void print()
    {
        std::cout << "--------------------" << std::endl;
        std::cout << "method: " << _method << " url: " << _url << " version: " << _http_version << std::endl;
        std::cout << "file path: " << _file_path << " suffix: " << _suffix << std::endl;
        for (size_t i = 0; i < _header.size(); ++i)
            std::cout << _header[i];
        std::cout << "--------body--------"<< std::endl;
        std::cout << _body;
        std::cout << "--------------------" << std::endl;
    }
    std::string serializer()
    {
        std::string req;
        for (size_t i = 0; i < _header.size(); ++i)
        {
            req += _header[i];
            req += "\r\n";
        }
        req += "\r\n";
        req += _body;
    }
    void parse()
    {
        std::stringstream ss(_header[0]);
        ss >> _method >> _url >> _http_version;
        _file_path = wwwroot;
        if (_url == "/" || _url == "/index.html")
        {
            _file_path += '/';
            _file_path += homepage;
        }
        else
            _file_path += _url;
        size_t pos = _file_path.rfind(".");
        if (pos == std::string::npos)
            _suffix = ".html";
        else
            _suffix = _file_path.substr(pos);
    }
public:
    std::vector<std::string> _header;
    std::string _body;

    std::string _method;
    std::string _url;
    std::string _http_version;
    
    // 请求的文件路径
    std::string _file_path;
    // 文件后缀
    std::string _suffix;
};